package com.ubis.ibms.plugin.views;


import java.util.ArrayList;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.ubis.ibms.plugin.composites.company.CompanyQueryComposite;
import com.ubis.ibms.plugin.composites.pay.PayAddComposite;
import com.ubis.ibms.plugin.composites.pay.PayQueryComposite;
import com.ubis.ibms.plugin.composites.recharge.RechargeQueryComposite;


/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class PropertyView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "ibms_plugin.views.PropertyView";

	private TreeViewer viewer;
	private Tree tree;
	private DrillDownAdapter drillDownAdapter;
	private Action action1;
	private Action action2;
	private Action doubleClickAction;
//	private Composite composite;

	/*
	 * The content provider class is responsible for
	 * providing objects to the view. It can wrap
	 * existing objects in adapters or simply return
	 * objects as-is. These objects may be sensitive
	 * to the current input of the view, or ignore
	 * it and always show the same content 
	 * (like Task List, for example).
	 */
	 
	class TreeObject implements IAdaptable {
		private String name;
		private TreeParent parent;
		
		public TreeObject(String name) {
			this.name = name;
		}
		public String getName() {
			return name;
		}
		public void setParent(TreeParent parent) {
			this.parent = parent;
		}
		public TreeParent getParent() {
			return parent;
		}
		public String toString() {
			return getName();
		}
		public Object getAdapter(Class key) {
			return null;
		}
	}
	
	class TreeParent extends TreeObject {
		private ArrayList children;
		public TreeParent(String name) {
			super(name);
			children = new ArrayList();
		}
		public void addChild(TreeObject child) {
			children.add(child);
			child.setParent(this);
		}
		public void removeChild(TreeObject child) {
			children.remove(child);
			child.setParent(null);
		}
		public TreeObject [] getChildren() {
			return (TreeObject [])children.toArray(new TreeObject[children.size()]);
		}
		public boolean hasChildren() {
			return children.size()>0;
		}
	}

	class ViewContentProvider implements IStructuredContentProvider, 
										   ITreeContentProvider {
		private TreeParent invisibleRoot;

		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}
		public void dispose() {
		}
		public Object[] getElements(Object parent) {
			if (parent.equals(getViewSite())) {
				if (invisibleRoot==null) initialize();
				return getChildren(invisibleRoot);
			}
			return getChildren(parent);
		}
		public Object getParent(Object child) {
			if (child instanceof TreeObject) {
				return ((TreeObject)child).getParent();
			}
			return null;
		}
		public Object [] getChildren(Object parent) {
			if (parent instanceof TreeParent) {
				return ((TreeParent)parent).getChildren();
			}
			return new Object[0];
		}
		public boolean hasChildren(Object parent) {
			if (parent instanceof TreeParent)
				return ((TreeParent)parent).hasChildren();
			return false;
		}
/*
 * We will set up a dummy model to initialize tree heararchy.
 * In a real code, you will connect to a real model and
 * expose its hierarchy.
 */
		private void initialize() {
//			TreeObject to1 = new TreeObject("业主登记");
			TreeObject toComanyQuery = new TreeObject("业主查询");
//			TreeObject to3 = new TreeObject("租赁登记");
			TreeParent tpCompanyMng = new TreeParent("业主管理");
//			p1.addChild(to1);
			tpCompanyMng.addChild(toComanyQuery);
//			p1.addChild(to3);
			
//			TreeObject to4 = new TreeObject("账户充值");
			TreeObject toRechargeRecord = new TreeObject("充值记录");
			TreeParent tpRechargeMng = new TreeParent("充值管理");
//			p2.addChild(to4);
			tpRechargeMng.addChild(toRechargeRecord);
			
//			TreeObject to6 = new TreeObject("交物业费");
			TreeObject toPayCalc = new TreeObject("消费结算");
			TreeObject toPayRecord = new TreeObject("消费记录");
			TreeParent tpPayMng = new TreeParent("消费管理");
//			p3.addChild(to6);
			tpPayMng.addChild(toPayCalc);
			tpPayMng.addChild(toPayRecord);
			
//			TreeObject to9 = new TreeObject("员工登记");
			TreeObject toWorkerQuery = new TreeObject("员工查询");
//			TreeObject to11 = new TreeObject("员工信息");
			TreeParent tpWorkerMng = new TreeParent("员工管理");
			tpWorkerMng.addChild(toWorkerQuery);
//			p4.addChild(to10);
//			p4.addChild(to11);
			
			TreeObject toTaskQuery = new TreeObject("工作查询");
//			TreeObject toTaskInfo = new TreeObject("工作信息");
			TreeParent tpTaskMng = new TreeParent("工作管理");
			tpTaskMng.addChild(toTaskQuery);
//			p5.addChild(to13);
			
			TreeObject toPerfAttend = new TreeObject("考勤统计");
			TreeObject toPerfTask = new TreeObject("工作考核");
			TreeObject toPerfAssess = new TreeObject("工作统计");
			TreeParent tpPerfMng = new TreeParent("绩效管理");
			tpPerfMng.addChild(toPerfAttend);
			tpPerfMng.addChild(toPerfTask);
			tpPerfMng.addChild(toPerfAssess);
			
			TreeParent root = new TreeParent("Root");
			root.addChild(tpCompanyMng);
			root.addChild(tpRechargeMng);
			root.addChild(tpPayMng);
			root.addChild(tpWorkerMng);
			root.addChild(tpTaskMng);
			root.addChild(tpPerfMng);
			
			invisibleRoot = new TreeParent("");
			invisibleRoot.addChild(root);
		}
	}
	class ViewLabelProvider extends LabelProvider {

		public String getText(Object obj) {
			return obj.toString();
		}
		public Image getImage(Object obj) {
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if (obj instanceof TreeParent)
			   imageKey = ISharedImages.IMG_OBJ_FOLDER;
			return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
		}
	}
	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public PropertyView() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		Layout layout = new GridLayout(2, false);
		parent.setLayout(layout);
		
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		tree = viewer.getTree();
		GridData treeGridData = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
		treeGridData.widthHint = 150;
		tree.setLayoutData(treeGridData);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
//		viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());
		//选中结点时收起或展开
		tree.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				TreeItem item = (TreeItem) e.item;
				if (item.getItemCount() > 0) {
					item.setExpanded(!item.getExpanded());
				}
			}
		});
		viewer.addSelectionChangedListener(new ISelectionChangedListener(){
			public void selectionChanged(SelectionChangedEvent event) {
				Object object = ((IStructuredSelection)event.getSelection()).getFirstElement();
				if(object instanceof TreeParent){
					TreeParent item = (TreeParent)object;
					String text = item.getName();
				}
				else if(object instanceof TreeObject){
					TreeObject item = (TreeObject)object;
					String text = item.getName();
//					if(text.equals("业主登记")){
//						//如果已经在业主登记页面，则什么都不做，否则切换到业主登记页面
////						changeToComposite(CompanyAddComposite.class);
//						Composite composite = (Composite)viewer.getControl().getParent().getChildren()[1];
//						if(composite instanceof CompanyAddComposite)
//							return;
//						composite.dispose();
//						composite = new CompanyAddComposite(viewer.getControl().getParent(), SWT.BORDER);
//						composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
//						composite.getParent().layout();
//					}
					if(text.equals("业主查询")){
						//如果已经在业主查询页面，则什么都不做，否则切换到业主查询页面
//						changeToComposite(CompanyQueryComposite.class);
						Composite composite = (Composite)viewer.getControl().getParent().getChildren()[1];
						if(composite instanceof CompanyQueryComposite)
							return;
						composite.dispose();
						composite = new CompanyQueryComposite(viewer.getControl().getParent(), SWT.BORDER);
						composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
						composite.getParent().layout();
					}
					else if(text.equals("充值记录")){
						//如果已经在充值记录页面，则什么都不做，否则切换到充值记录页面
						Composite composite = (Composite)viewer.getControl().getParent().getChildren()[1];
						if(composite instanceof RechargeQueryComposite)
							return;
						composite.dispose();
						composite = new RechargeQueryComposite(viewer.getControl().getParent(), SWT.BORDER);
						composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
						composite.getParent().layout();
					}
					else if(text.equals("消费结算")){
						//如果已经在消费结算页面，则什么都不做，否则切换到消费结算页面
						Composite composite = (Composite)viewer.getControl().getParent().getChildren()[1];
						if(composite instanceof PayAddComposite)
							return;
						composite.dispose();
						composite = new PayAddComposite(viewer.getControl().getParent(), SWT.BORDER);
						composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
						composite.getParent().layout();
					}
					else if(text.equals("消费记录")){
						//如果已经在消费记录页面，则什么都不做，否则切换到消费记录页面
						Composite composite = (Composite)viewer.getControl().getParent().getChildren()[1];
						if(composite instanceof PayQueryComposite)
							return;
						composite.dispose();
						composite = new PayQueryComposite(viewer.getControl().getParent(), SWT.BORDER);
						composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
						composite.getParent().layout();
					}
				}
			}
		});
		tree.addSelectionListener(new SelectionListener(){
			public void widgetDefaultSelected(SelectionEvent event) {
			}
			public void widgetSelected(SelectionEvent event) {
				TreeItem item = (TreeItem)event.item;
				String text = item.getText();
			}
			
		});
		
		Composite composite = new Composite(parent, SWT.BORDER);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "ibms_plugin.viewer");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

//	public <T> void changeToComposite(Class<T> clazz) {
//		Composite composite = (Composite)viewer.getControl().getParent().getChildren()[1];
//		if(clazz.isInstance(composite))
//			return;
//		composite.dispose();
//		try{
//			composite = (Composite)(clazz.getConstructor(Composite.class, Integer.class).newInstance(viewer.getControl().getParent(), SWT.BORDER));
//		}catch(Exception e){
//			e.printStackTrace();
//		}
////		composite = new CompanyAddComposite(viewer.getControl().getParent(), SWT.BORDER);
//		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
//		composite.getParent().layout();
//	}
	
	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				PropertyView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				showMessage("Action 1 executed");
			}
		};
		action1.setText("Action 1");
		action1.setToolTipText("Action 1 tooltip");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		action2 = new Action() {
			public void run() {
				showMessage("Action 2 executed");
			}
		};
		action2.setText("Action 2");
		action2.setToolTipText("Action 2 tooltip");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				showMessage("Double-click detected on "+obj.toString());
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"物业管理",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}